﻿#include "TicketAdminDialog.h"
#include "ChangeTicketDialog.h"
#include <Global_Class.h>
#include <orders.h>
#include <seats.h>
#include <stations.h>
#include <trains.h>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QInputDialog>
#include <Constants.h>
using namespace Constants;

//TicketAdminDialog::TicketAdminDialog(QWidget* parent) : QDialog(parent) {
//    setWindowTitle("车票管理（订单管理）");
//    resize(1200, 700); // 增大窗口宽度
//    QVBoxLayout* mainLayout = new QVBoxLayout(this);
//    QHBoxLayout* filterLayout = new QHBoxLayout();
//    searchEdit = new QLineEdit(this);
//    searchEdit->setPlaceholderText("订单号/用户ID/车次/座位号/日期");
//    statusCombo = new QComboBox(this);
//    statusCombo->addItem("全部状态", -1);
//    statusCombo->addItem("已预订", orders::booked);
//    statusCombo->addItem("已退票", orders::canceled);
//    statusCombo->addItem("已改签", orders::changed);
//    seatTypeCombo = new QComboBox(this);
//    seatTypeCombo->addItem("全部座型", "");
//    seatTypeCombo->addItem("商务座", "商务座");
//    seatTypeCombo->addItem("一等座", "一等座");
//    seatTypeCombo->addItem("二等座", "二等座");
//    // 新增出发站/到达站下拉框
//    startStationCombo = new QComboBox(this);
//    endStationCombo = new QComboBox(this);
//    startStationCombo->addItem("全部出发站", "");
//    endStationCombo->addItem("全部到达站", "");
//    QSet<QString> startSet, endSet;
//    for (const auto& st : allData->stationsQueue) {
//        startSet.insert(QString::fromStdString(st.getName()));
//        endSet.insert(QString::fromStdString(st.getName()));
//    }
//    for (const auto& s : startSet) startStationCombo->addItem(s, s);
//    for (const auto& s : endSet) endStationCombo->addItem(s, s);
//    btnSearch = new QPushButton("查询", this);
//    filterLayout->addWidget(new QLabel("筛选："));
//    filterLayout->addWidget(searchEdit);
//    filterLayout->addWidget(statusCombo);
//    filterLayout->addWidget(seatTypeCombo);
//    filterLayout->addWidget(startStationCombo);
//    filterLayout->addWidget(endStationCombo);
//    filterLayout->addWidget(btnSearch);
//    btnDelete = new QPushButton("批量删除", this);
//    filterLayout->addWidget(btnDelete);
//    btnEditPrice = new QPushButton("改价", this);
//    filterLayout->addWidget(btnEditPrice);
//	btnUndo = new QPushButton("撤销", this);
//	btnRedo = new QPushButton("恢复", this);
//	filterLayout->addWidget(btnUndo);
//	filterLayout->addWidget(btnRedo);
//    filterLayout->addStretch();
//    mainLayout->addLayout(filterLayout);
//    table = new QTableWidget(this);
//    table->setColumnCount(14);
//    table->setHorizontalHeaderLabels({"订单号", "用户ID", "车次", "出发站", "到达站", "座位号", "座型", "日期", "票价", "状态", "下单时间", "详情", "退票", "改签"});
//    for (int i = 0; i < 14; ++i) {
//        table->horizontalHeader()->setSectionResizeMode(i, QHeaderView::Stretch);
//    }
//    table->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
//    table->setSelectionBehavior(QAbstractItemView::SelectRows);
//    table->setSelectionMode(QAbstractItemView::ExtendedSelection);
//    mainLayout->addWidget(table);
//    connect(btnSearch, &QPushButton::clicked, this, [this]() {
//        loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
//            startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
//    });
//    connect(btnDelete, &QPushButton::clicked, this, [this]() { deleteSelectedOrder(); });
//    connect(btnEditPrice, &QPushButton::clicked, this, [this]() { editSelectedOrderPrice(); });
//
//    connect(btnUndo, &QPushButton::clicked, this, [this]() {
//        if (undoRedo.undoAction()) {
//            loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
//                startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
//            QMessageBox::information(this, "撤销", "撤销成功");
//        } else {
//            QMessageBox::warning(this, "撤销", "没有可撤销的操作");
//        }
//		});
//    connect(btnRedo, &QPushButton::clicked, this, [this]() {
//        if (undoRedo.redoAction()) {
//            loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
//                startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
//            QMessageBox::information(this, "恢复", "恢复成功");
//        } else {
//            QMessageBox::warning(this, "恢复", "没有可恢复的操作");
//        }
//		});
//    loadAllOrders();
//}
//
//void TicketAdminDialog::loadAllOrders(const QString& keyword, int statusFilter, const QString& seatType, const QString& startStationFilter, const QString& endStationFilter) {
//    table->setRowCount(0);
//    QString filterStart = startStationFilter, filterEnd = endStationFilter;
//    if (filterStart == "") filterStart.clear();
//    if (filterEnd == "") filterEnd.clear();
//    for (size_t i = 0; i < allData->ordersQueue.size(); ++i) {
//        const auto& order = allData->ordersQueue[i];
//        if (statusFilter != -1 && order.getStatus() != statusFilter) continue;
//        QString orderIdStr = QString::number(order.getOrderId());
//        QString userIdStr = QString::number(order.getUserId());
//        QString trainCode = "";
//        for (const auto& train : allData->trainQueue) {
//            if (train.getTrainId() == order.getTrainId()) {
//                trainCode = QString::fromStdString(train.getTrainCode());
//                break;
//            }
//        }
//        QString seatNo = "";
//        std::string seatTypeStr = "";
//        for (const auto& seat : allData->seatsQueue) {
//            if (seat.getSeatId() == order.getSeatId()) {
//                seatNo = QString::fromStdString(seat.getSeatNo());
//                seatTypeStr = seat.getSeatType();
//                break;
//            }
//        }
//        if (!seatType.isEmpty() && seatTypeStr != seatType.toStdString()) continue;
//        QString startStation = "", endStation = "";
//        for (const auto& st : allData->stationsQueue) {
//            if (st.getStationId() == order.getStartStationId()) startStation = QString::fromStdString(st.getName());
//            if (st.getStationId() == order.getEndStationId()) endStation = QString::fromStdString(st.getName());
//        }
//        // 新增下拉框筛选
//        if (!filterStart.isEmpty() && startStation != filterStart) continue;
//        if (!filterEnd.isEmpty() && endStation != filterEnd) continue;
//        QString dateStr = QString::fromStdString(order.getTravelDate());
//        double price = order.getPrice();
//        QString priceStr = price < 0 ? "-" : QString::number(price, 'f', 2);
//        QString statusStr;
//        switch (order.getStatus()) {
//            case orders::booked: statusStr = "已预订"; break;
//            case orders::canceled: statusStr = "已退票"; break;
//            case orders::changed: statusStr = "已改签"; break;
//            default: statusStr = "未知"; break;
//        }
//        QString orderTime = QString::fromStdString(order.getOrderTime());
//        // 其他关键字模糊匹配
//        if (!keyword.isEmpty()) {
//            if (!orderIdStr.contains(keyword) && !userIdStr.contains(keyword) && !trainCode.contains(keyword)
//                && !seatNo.contains(keyword) && !dateStr.contains(keyword) && !startStation.contains(keyword) && !endStation.contains(keyword)) continue;
//        }
//        int row = table->rowCount();
//        table->insertRow(row);
//        table->setItem(row, 0, new QTableWidgetItem(orderIdStr));
//        table->setItem(row, 1, new QTableWidgetItem(userIdStr));
//        table->setItem(row, 2, new QTableWidgetItem(trainCode));
//        table->setItem(row, 3, new QTableWidgetItem(startStation));
//        table->setItem(row, 4, new QTableWidgetItem(endStation));
//        table->setItem(row, 5, new QTableWidgetItem(seatNo));
//        table->setItem(row, 6, new QTableWidgetItem(QString::fromStdString(seatTypeStr)));
//        table->setItem(row, 7, new QTableWidgetItem(dateStr));
//        table->setItem(row, 8, new QTableWidgetItem(priceStr));
//        table->setItem(row, 9, new QTableWidgetItem(statusStr));
//        table->setItem(row, 10, new QTableWidgetItem(orderTime));
//        // 详情按钮
//        QPushButton* btnDetail = new QPushButton("详情");
//        table->setCellWidget(row, 11, btnDetail);
//        connect(btnDetail, &QPushButton::clicked, this, [this, row]() { showOrderDetail(row); });
//        // 退票按钮
//        QPushButton* btnRefund = new QPushButton("退票");
//        btnRefund->setEnabled(order.getStatus() == orders::booked);
//        table->setCellWidget(row, 12, btnRefund);
//        connect(btnRefund, &QPushButton::clicked, this, [this, row]() { refundOrder(row); });
//        // 改签按钮
//        QPushButton* btnChange = new QPushButton("改签");
//        btnChange->setEnabled(order.getStatus() == orders::booked);
//        table->setCellWidget(row, 13, btnChange);
//        connect(btnChange, &QPushButton::clicked, this, [this, row]() { changeOrder(row); });
//    }
//}
//
void TicketAdminDialog::editPrice(int row) {
    int orderId = table->item(row, 0)->text().toInt();
    double oldPrice = table->item(row, 8)->text().toDouble();
    bool ok = false;
    double newPrice = QInputDialog::getDouble(this, "修改票价", "请输入新票价：", oldPrice, 0, 10000, 2, &ok);
    if (!ok) return;
    for (auto& order : allData->ordersQueue) {
        if (order.getOrderId() == orderId) {
            order.setPrice(newPrice);
            allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
            break;
        }
    }
    table->setItem(row, 8, new QTableWidgetItem(QString::number(newPrice, 'f', 2)));
    QMessageBox::information(this, "改价", "票价已修改并保存");
}

void TicketAdminDialog::showOrderDetail(int row) {
    int orderId = table->item(row, 0)->text().toInt();
    const orders* orderPtr = nullptr;
    for (const auto& o : allData->ordersQueue) {
        if (o.getOrderId() == orderId) { orderPtr = &o; break; }
    }
    QString info;
    info += table->horizontalHeaderItem(0)->text() + ": " + (table->item(row, 0) ? table->item(row, 0)->text() : "") + "\n";
    if (orderPtr) {
        for (const auto& u : allData->usersQueue) {
            if (u.getUserId() == QString::number(orderPtr->getUserId()).toStdString()) {
                info += "昵称: " + QString::fromStdString(u.getDisplayName()) + "\n";
                info += "手机号: " + QString::fromStdString(u.getPhone()) + "\n";
                info += "身份证号: " + QString::fromStdString(u.getIdCard()) + "\n";
                break;
            }
        }
    }
    for (int col = 1; col <= 10; ++col) {
        info += table->horizontalHeaderItem(col)->text() + ": " + (table->item(row, col) ? table->item(row, col)->text() : "") + "\n";
    }

    QMessageBox::information(this, "订单详情", info);
}

void TicketAdminDialog::refundOrder(int row) {
    int orderId = table->item(row, 0)->text().toInt();
    for (auto& order : allData->ordersQueue) {
        if (order.getOrderId() == orderId && order.getStatus() == orders::booked) {
            order.setStatus(orders::canceled);
            allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
            loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString());
            QMessageBox::information(this, "退票", "退票成功");
            return;
        }
    }
    QMessageBox::warning(this, "退票", "退票失败，订单状态异常");
}

void TicketAdminDialog::changeOrder(int row) {
    int orderId = table->item(row, 0)->text().toInt();
    for (auto& order : allData->ordersQueue) {
        if (order.getOrderId() == orderId && order.getStatus() == orders::booked) {
            ChangeTicketDialog dlg(order, this);
            if (dlg.exec() == QDialog::Accepted && dlg.isSuccess()) {
                order.setStatus(orders::changed);
                allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
                orders newOrder = order;
                newOrder.setOrderId(allData->ordersQueue.empty() ? 1 : allData->ordersQueue.back().getOrderId() + 1);
                newOrder.setTrainId(dlg.getNewTrainId());
                newOrder.setSeatId(dlg.getNewSeatId());
                newOrder.setTravelDate(dlg.getNewDate());
                newOrder.setStatus(orders::booked);
                newOrder.setOrderTime(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toStdString());
                allData->ordersQueue.push_back(newOrder);
                allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
                loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString());
                QMessageBox::information(this, "改签", QString("改签成功，新订单号：%1").arg(newOrder.getOrderId()));
            }
            return;
        }
    }
    QMessageBox::warning(this, "改签", "改签失败，订单状态异常");
}

void TicketAdminDialog::deleteSelectedOrder() {
    auto selectedRows = table->selectionModel()->selectedRows();
    if (selectedRows.isEmpty()) {
        QMessageBox::warning(this, "删除", "请先选中要删除的订单行");
        return;
    }
    int ret = QMessageBox::question(this, "批量删除订单", QString("确定要删除选中的%1个订单吗？").arg(selectedRows.size()), QMessageBox::Yes | QMessageBox::No);
    if (ret != QMessageBox::Yes) return;
    QSet<int> orderIdsToDelete;
    QSet<int> rowSet;
    for (const auto& idx : selectedRows) {
        int row = idx.row();
        rowSet.insert(row);
        int orderId = table->item(row, 0)->text().toInt();
        orderIdsToDelete.insert(orderId);
    }
    QList<int> rows = rowSet.values();
    std::sort(rows.begin(), rows.end(), std::greater<int>());

    Operation_o op;
    op.type = Delete;

    for (int row : rows) {
		const QString id = table->item(row, 0)->text();
        auto it = std::find_if(allData->ordersQueue.begin(), allData->ordersQueue.end(),
			[&](orders& ord) { return ord.getOrderId() == id.toInt();
            });
        if (it != allData->ordersQueue.end()) {
            op.Orders.push_back(*it);
            op.indices.push_back(row);   // 原位置
        }
    }
    undoRedo.recordOp(op);               // ★ 先记录，再执行下面的删除循环

    int before = allData->ordersQueue.size();
    allData->ordersQueue.erase(
        std::remove_if(allData->ordersQueue.begin(), allData->ordersQueue.end(),
            [&](const orders& o) { return orderIdsToDelete.contains(o.getOrderId()); }),
        allData->ordersQueue.end());
    int after = allData->ordersQueue.size();
    allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
    loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
        startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
    QMessageBox::information(this, "删除", QString("已删除%1个订单").arg(before - after));
}


void TicketAdminDialog::editSelectedOrderPrice() {
    int row = table->currentRow();
    if (row < 0) {
        QMessageBox::warning(this, "改价", "请先选中要改价的订单行");
        return;
    }
    int orderId = table->item(row, 0)->text().toInt();
    double oldPrice = table->item(row, 8)->text().toDouble();
    bool ok = false;
    double newPrice = QInputDialog::getDouble(this, "修改票价", "请输入新票价：", oldPrice, 0, 10000, 2, &ok);
    if (!ok) return;
    for (auto& order : allData->ordersQueue) {
        if (order.getOrderId() == orderId) {


            orders old = order;          // 复制旧对象

            order.setPrice(newPrice);

            orders edited = order;
            // —— 记录 —— 
            Operation_o op;
            op.type = Modify;
            op.Orders = { old, edited };  // 0 = 旧, 1 = 新
            op.indices = { row };
            undoRedo.recordOp(op);

            //allData->Order_WriteToFile(ORDER_INFORMATION_FILE_POSITION);
            break;
        }
    }

    table->setItem(row, 8, new QTableWidgetItem(QString::number(newPrice, 'f', 2)));
    QMessageBox::information(this, "改价", "票价已修改并保存");
}

//以下是优化UI的版本欧~--------------------------------------------------------------------------------
// 在loadAllOrders函数中添加样式优化
void TicketAdminDialog::loadAllOrders(const QString& keyword, int statusFilter, const QString& seatType, const QString& startStationFilter, const QString& endStationFilter) {
    table->setRowCount(0);
    QString filterStart = startStationFilter, filterEnd = endStationFilter;
    if (filterStart == "") filterStart.clear();
    if (filterEnd == "") filterEnd.clear();

    int orderCount = 0;

    // 创建操作按钮的样式
    auto createActionButton = [this](const QString& text, const QString& color, const QString& hoverColor) {
        QPushButton* btn = new QPushButton(text, this);
        btn->setMinimumSize(60, 28);
        btn->setCursor(Qt::PointingHandCursor);

        QString style = QString(
            "QPushButton { "
            "    background-color: %1; "
            "    color: white; "
            "    border: none; "
            "    border-radius: 4px; "
            "    padding: 4px 8px; "
            "    font-size: 9pt; "
            "    font-weight: bold; "
            "} "
            "QPushButton:hover { "
            "    background-color: %2; "
            "} "
            "QPushButton:pressed { "
            "    background-color: %1; "
            "} "
            "QPushButton:disabled { "
            "    background-color: #bdc3c7; "
            "    color: #7f8c8d; "
            "}"
        ).arg(color, hoverColor);

        btn->setStyleSheet(style);
        return btn;
        };

    for (size_t i = 0; i < allData->ordersQueue.size(); ++i) {
        const auto& order = allData->ordersQueue[i];
        if (statusFilter != -1 && order.getStatus() != statusFilter) continue;
        QString orderIdStr = QString::number(order.getOrderId());
        QString userIdStr = QString::number(order.getUserId());
        QString trainCode = "";
        for (const auto& train : allData->trainQueue) {
            if (train.getTrainId() == order.getTrainId()) {
                trainCode = QString::fromStdString(train.getTrainCode());
                break;
            }
        }
        QString seatNo = "";
        std::string seatTypeStr = "";
        for (const auto& seat : allData->seatsQueue) {
            if (seat.getSeatId() == order.getSeatId()) {
                seatNo = QString::fromStdString(seat.getSeatNo());
                seatTypeStr = seat.getSeatType();
                break;
            }
        }
        if (!seatType.isEmpty() && seatTypeStr != seatType.toStdString()) continue;
        QString startStation = "", endStation = "";
        for (const auto& st : allData->stationsQueue) {
            if (st.getStationId() == order.getStartStationId()) startStation = QString::fromStdString(st.getName());
            if (st.getStationId() == order.getEndStationId()) endStation = QString::fromStdString(st.getName());
        }
        // 新增下拉框筛选
        if (!filterStart.isEmpty() && startStation != filterStart) continue;
        if (!filterEnd.isEmpty() && endStation != filterEnd) continue;
        QString dateStr = QString::fromStdString(order.getTravelDate());
        double price = order.getPrice();
        QString priceStr = price < 0 ? "-" : QString::number(price, 'f', 2);
        QString statusStr;
        QString statusColor;
        switch (order.getStatus()) {
        case orders::booked:
            statusStr = "已预订";
            statusColor = "#27ae60";
            break;
        case orders::canceled:
            statusStr = "已退票";
            statusColor = "#e74c3c";
            break;
        case orders::changed:
            statusStr = "已改签";
            statusColor = "#3498db";
            break;
        default:
            statusStr = "未知";
            statusColor = "#95a5a6";
            break;
        }
        QString orderTime = QString::fromStdString(order.getOrderTime());
        // 其他关键字模糊匹配
        if (!keyword.isEmpty()) {
            if (!orderIdStr.contains(keyword) && !userIdStr.contains(keyword) && !trainCode.contains(keyword)
                && !seatNo.contains(keyword) && !dateStr.contains(keyword) && !startStation.contains(keyword) && !endStation.contains(keyword)) continue;
        }
        int row = table->rowCount();
        table->insertRow(row);

        // 设置表格项，添加颜色样式
        table->setItem(row, 0, new QTableWidgetItem(orderIdStr));
        table->setItem(row, 1, new QTableWidgetItem(userIdStr));
        table->setItem(row, 2, new QTableWidgetItem(trainCode));
        table->setItem(row, 3, new QTableWidgetItem(startStation));
        table->setItem(row, 4, new QTableWidgetItem(endStation));
        table->setItem(row, 5, new QTableWidgetItem(seatNo));
        table->setItem(row, 6, new QTableWidgetItem(QString::fromStdString(seatTypeStr)));
        table->setItem(row, 7, new QTableWidgetItem(dateStr));

        QTableWidgetItem* priceItem = new QTableWidgetItem(priceStr);
        if (price >= 0) {
            priceItem->setForeground(QColor("#e67e22")); // 橙色显示价格
        }
        table->setItem(row, 8, priceItem);

        QTableWidgetItem* statusItem = new QTableWidgetItem(statusStr);
        statusItem->setForeground(QColor(statusColor));
        table->setItem(row, 9, statusItem);

        table->setItem(row, 10, new QTableWidgetItem(orderTime));

        // 详情按钮
        QPushButton* btnDetail = createActionButton("详情", "#3498db", "#2980b9");
        table->setCellWidget(row, 11, btnDetail);
        connect(btnDetail, &QPushButton::clicked, this, [this, row]() { showOrderDetail(row); });

        // 退票按钮
        QPushButton* btnRefund = createActionButton("退票", "#e74c3c", "#c0392b");
        btnRefund->setEnabled(order.getStatus() == orders::booked);
        table->setCellWidget(row, 12, btnRefund);
        connect(btnRefund, &QPushButton::clicked, this, [this, row]() { refundOrder(row); });

        // 改签按钮
        QPushButton* btnChange = createActionButton("改签", "#f39c12", "#e67e22");
        btnChange->setEnabled(order.getStatus() == orders::booked);
        table->setCellWidget(row, 13, btnChange);
        connect(btnChange, &QPushButton::clicked, this, [this, row]() { changeOrder(row); });

        orderCount++;
    }

    // 更新订单计数
    orderCountLabel->setText(QString("总计: %1 个订单").arg(orderCount));

    // 如果没有订单，显示提示信息
    if (table->rowCount() == 0) {
        table->setRowCount(1);
        QTableWidgetItem* noOrderItem = new QTableWidgetItem("没有找到符合条件的订单");
        noOrderItem->setTextAlignment(Qt::AlignCenter);
        noOrderItem->setForeground(QColor("#7f8c8d"));
        table->setItem(0, 0, noOrderItem);
        table->setSpan(0, 0, 1, 14); // 合并所有列
    }
}

TicketAdminDialog::TicketAdminDialog(QWidget* parent) : QDialog(parent) {
    setWindowTitle("车票管理（订单管理）");
    setMinimumSize(1400, 800);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

    setupUI();
    setupConnections();
    setupStyles();
    loadAllOrders();
}

void TicketAdminDialog::setupUI() {
    // 主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    setupTitleSection(mainLayout);
    setupFilterSection(mainLayout);
    setupTableSection(mainLayout);
    setupStatusSection(mainLayout);
}

void TicketAdminDialog::setupTitleSection(QVBoxLayout* mainLayout) {
    QLabel* titleLabel = new QLabel("订单管理系统", this);
    titleLabel->setFont(QFont("Microsoft YaHei", 16, QFont::Bold));
    titleLabel->setStyleSheet("color: #2c3e50; padding: 8px 0;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);
}

void TicketAdminDialog::setupFilterSection(QVBoxLayout* mainLayout) {
    QFrame* filterFrame = new QFrame(this);
    filterFrame->setFrameStyle(QFrame::StyledPanel);
    filterFrame->setStyleSheet(
        "QFrame {"
        "    background-color: #f8f9fa;"
        "    border: 1px solid #e0e0e0;"
        "    border-radius: 8px;"
        "    padding: 15px;"
        "}"
    );

    QVBoxLayout* filterMainLayout = new QVBoxLayout(filterFrame);
    filterMainLayout->setSpacing(12);

    // 筛选标题
    QLabel* filterTitle = new QLabel("筛选条件", this);
    filterTitle->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    filterTitle->setStyleSheet("color: #34495e; margin-bottom: 8px;");
    filterMainLayout->addWidget(filterTitle);

    setupSearchControls(filterMainLayout);
    setupActionButtons(filterMainLayout);

    mainLayout->addWidget(filterFrame);
}

void TicketAdminDialog::setupSearchControls(QVBoxLayout* filterMainLayout) {
    QHBoxLayout* filterLayout = new QHBoxLayout();
    filterLayout->setSpacing(12);

    // 搜索框
    searchEdit = new QLineEdit(this);
    searchEdit->setPlaceholderText("订单号/用户ID/车次/座位号/日期...");
    searchEdit->setMinimumWidth(200);
    searchEdit->setClearButtonEnabled(true);

    // 状态筛选
    statusCombo = new QComboBox(this);
    statusCombo->setMinimumWidth(120);
    statusCombo->addItem("全部状态", -1);
    statusCombo->addItem("已预订", orders::booked);
    statusCombo->addItem("已退票", orders::canceled);
    statusCombo->addItem("已改签", orders::changed);

    // 座位类型筛选
    seatTypeCombo = new QComboBox(this);
    seatTypeCombo->setMinimumWidth(120);
    seatTypeCombo->addItem("全部座型", "");
    seatTypeCombo->addItem("商务座", "商务座");
    seatTypeCombo->addItem("一等座", "一等座");
    seatTypeCombo->addItem("二等座", "二等座");

    // 站点筛选
    setupStationComboBoxes();

    // 查询按钮
    btnSearch = createButton("查询", "#3498db", "#2980b9", 80);

    // 添加筛选控件
    filterLayout->addWidget(new QLabel("🔍 搜索:", this));
    filterLayout->addWidget(searchEdit);
    filterLayout->addWidget(new QLabel("📊 状态:", this));
    filterLayout->addWidget(statusCombo);
    filterLayout->addWidget(new QLabel("💺 座型:", this));
    filterLayout->addWidget(seatTypeCombo);
    filterLayout->addWidget(new QLabel("🚂 出发站:", this));
    filterLayout->addWidget(startStationCombo);
    filterLayout->addWidget(new QLabel("🎯 到达站:", this));
    filterLayout->addWidget(endStationCombo);
    filterLayout->addWidget(btnSearch);

    filterMainLayout->addLayout(filterLayout);
}

void TicketAdminDialog::setupStationComboBoxes() {
    startStationCombo = new QComboBox(this);
    endStationCombo = new QComboBox(this);
    startStationCombo->setMinimumWidth(120);
    endStationCombo->setMinimumWidth(120);
    startStationCombo->addItem("全部出发站", "");
    endStationCombo->addItem("全部到达站", "");

    QSet<QString> startSet, endSet;
    for (const auto& st : allData->stationsQueue) {
        startSet.insert(QString::fromStdString(st.getName()));
        endSet.insert(QString::fromStdString(st.getName()));
    }
    for (const auto& s : startSet) startStationCombo->addItem(s, s);
    for (const auto& s : endSet) endStationCombo->addItem(s, s);
}

void TicketAdminDialog::setupActionButtons(QVBoxLayout* filterMainLayout) {
    // 操作按钮
    btnDelete = createButton("批量删除", "#e74c3c", "#c0392b", 90);
    btnEditPrice = createButton("修改票价", "#f39c12", "#e67e22", 90);
    btnUndo = createButton("撤销", "#95a5a6", "#7f8c8d", 70);
    btnRedo = createButton("恢复", "#95a5a6", "#7f8c8d", 70);

    // 操作按钮布局
    QHBoxLayout* actionLayout = new QHBoxLayout();
    actionLayout->setSpacing(10);
    actionLayout->addWidget(btnDelete);
    actionLayout->addWidget(btnEditPrice);
    actionLayout->addStretch();
    actionLayout->addWidget(btnUndo);
    actionLayout->addWidget(btnRedo);

    filterMainLayout->addLayout(actionLayout);
}

void TicketAdminDialog::setupTableSection(QVBoxLayout* mainLayout) {
    QFrame* tableFrame = new QFrame(this);
    tableFrame->setFrameStyle(QFrame::StyledPanel);
    tableFrame->setStyleSheet("QFrame { background-color: white; border-radius: 8px; }");

    QVBoxLayout* tableLayout = new QVBoxLayout(tableFrame);
    tableLayout->setContentsMargins(12, 12, 12, 12);

    // 表格标题栏
    QHBoxLayout* tableHeaderLayout = new QHBoxLayout();
    QLabel* tableTitle = new QLabel("订单列表", this);
    tableTitle->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    tableTitle->setStyleSheet("color: #34495e;");
    tableHeaderLayout->addWidget(tableTitle);
    tableHeaderLayout->addStretch();

    // 订单统计信息
    orderCountLabel = new QLabel("总计: 0 个订单", this);
    orderCountLabel->setStyleSheet("color: #7f8c8d; font-size: 9pt;");
    tableHeaderLayout->addWidget(orderCountLabel);
    tableLayout->addLayout(tableHeaderLayout);

    // 表格控件
    table = new QTableWidget(this);
    setupTableColumns();

    tableLayout->addWidget(table);
    mainLayout->addWidget(tableFrame, 1);
}

void TicketAdminDialog::setupTableColumns() {
    table->setColumnCount(14);
    table->setHorizontalHeaderLabels({
        "订单号", "用户ID", "车次", "出发站", "到达站", "座位号", "座型",
        "日期", "票价", "状态", "下单时间", "详情", "退票", "改签"
        });

    // 表格样式优化
    table->horizontalHeader()->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    table->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);

    // 设置合理的列宽
    table->setColumnWidth(0, 90);   // 订单号
    table->setColumnWidth(1, 80);   // 用户ID
    table->setColumnWidth(2, 100);  // 车次
    table->setColumnWidth(3, 120);  // 出发站
    table->setColumnWidth(4, 120);  // 到达站
    table->setColumnWidth(5, 80);   // 座位号
    table->setColumnWidth(6, 80);   // 座型
    table->setColumnWidth(7, 110);  // 日期
    table->setColumnWidth(8, 80);   // 票价
    table->setColumnWidth(9, 100);  // 状态
    table->setColumnWidth(10, 160); // 下单时间
    table->setColumnWidth(11, 70);  // 详情
    table->setColumnWidth(12, 70);  // 退票
    table->setColumnWidth(13, 70);  // 改签

    table->verticalHeader()->setVisible(false);
    table->setShowGrid(false);
    table->setAlternatingRowColors(true);
    table->setSortingEnabled(true);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setSelectionMode(QAbstractItemView::ExtendedSelection);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

void TicketAdminDialog::setupStatusSection(QVBoxLayout* mainLayout) {
    QHBoxLayout* statusLayout = new QHBoxLayout();
    QLabel* infoLabel = new QLabel("💡 提示：支持多选订单进行批量操作，双击订单可查看详细信息", this);
    infoLabel->setStyleSheet(
        "QLabel { "
        "    color: #7f8c8d; "
        "    padding: 8px 12px; "
        "    background-color: #ecf0f1; "
        "    border-radius: 4px; "
        "    font-size: 9pt; "
        "}"
    );
    infoLabel->setMinimumHeight(30);
    statusLayout->addWidget(infoLabel);
    mainLayout->addLayout(statusLayout);
}

void TicketAdminDialog::setupConnections() {
    connect(btnSearch, &QPushButton::clicked, this, [this]() {
        loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
            startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
        });
    connect(btnDelete, &QPushButton::clicked, this, [this]() { deleteSelectedOrder(); });
    connect(btnEditPrice, &QPushButton::clicked, this, [this]() { editSelectedOrderPrice(); });

    connect(btnUndo, &QPushButton::clicked, this, [this]() {
        if (undoRedo.undoAction()) {
            loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
                startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
            QMessageBox::information(this, "撤销", "撤销成功");
        }
        else {
            QMessageBox::warning(this, "撤销", "没有可撤销的操作");
        }
        });
    connect(btnRedo, &QPushButton::clicked, this, [this]() {
        if (undoRedo.redoAction()) {
            loadAllOrders(searchEdit->text(), statusCombo->currentData().toInt(), seatTypeCombo->currentData().toString(),
                startStationCombo->currentData().toString(), endStationCombo->currentData().toString());
            QMessageBox::information(this, "恢复", "恢复成功");
        }
        else {
            QMessageBox::warning(this, "恢复", "没有可恢复的操作");
        }
        });
}

void TicketAdminDialog::setupStyles() {
    // 设置控件样式
    QString lineEditStyle =
        "QLineEdit {"
        "    padding: 8px 12px;"
        "    border: 2px solid #e0e0e0;"
        "    border-radius: 6px;"
        "    background-color: white;"
        "    color: #2c3e50;"  // 深色文字
        "}"
        "QLineEdit:focus {"
        "    border-color: #3498db;"
        "}"
        "QLineEdit::placeholder {"
        "    color: #a0a0a0;"  // 浅色占位符文字
        "}";

    QString comboBoxStyle =
        "QComboBox {"
        "    padding: 8px 12px;"
        "    border: 2px solid #e0e0e0;"
        "    border-radius: 6px;"
        "    background-color: white;"
        "    color: #2c3e50;"  // 深色文字
        "    selection-background-color: #3498db;"
        "    selection-color: white;"
        "}"
        "QComboBox:focus {"
        "    border-color: #3498db;"
        "}"
        "QComboBox::drop-down {"
        "    border: none;"
        "    width: 30px;"
        "}"
        "QComboBox::down-arrow {"
        "    image: none;"
        "    border-left: 5px solid transparent;"
        "    border-right: 5px solid transparent;"
        "    border-top: 5px solid #7f8c8d;"
        "}"
        "QComboBox QAbstractItemView {"
        "    background-color: white;"
        "    border: 1px solid #e0e0e0;"
        "    border-radius: 6px;"
        "    selection-background-color: #3498db;"
        "    selection-color: white;"
        "    outline: none;"
        "}"
        "QComboBox QAbstractItemView::item {"
        "    color: #2c3e50;"  // 下拉列表项的文字颜色
        "    padding: 8px 12px;"
        "    border: none;"
        "}"
        "QComboBox QAbstractItemView::item:hover {"
        "    background-color: #f0f0f0;"
        "}"
        "QComboBox QAbstractItemView::item:selected {"
        "    background-color: #3498db;"
        "    color: white;"
        "}";

    searchEdit->setStyleSheet(lineEditStyle);
    statusCombo->setStyleSheet(comboBoxStyle);
    seatTypeCombo->setStyleSheet(comboBoxStyle);
    startStationCombo->setStyleSheet(comboBoxStyle);
    endStationCombo->setStyleSheet(comboBoxStyle);

    // 设置全局样式表
    setStyleSheet(R"(
        /* 主窗口样式 */
        QDialog {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #f5f7fa, stop: 1 #e4e7ec);
            color: #333333;
        }

        /* 表格样式优化 */
        QTableWidget {
            background-color: white;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            gridline-color: #f0f0f0;
            outline: none;
        }
        QTableWidget::item {
            border: none;
            padding: 8px 12px;
            color: #2c3e50;
            border-bottom: 1px solid #f8f9fa;
        }
        QTableWidget::item:selected {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        QTableWidget::item:hover {
            background-color: #f5f5f5;
        }
        QTableWidget::item:alternate {
            background-color: #fafbfc;
        }
        QHeaderView::section {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #34495e, stop: 1 #2c3e50);
            color: white;
            padding: 12px 8px;
            border: none;
            font-weight: bold;
            border-right: 1px solid #455a64;
        }
        QHeaderView::section:last {
            border-right: none;
        }

        /* 标签样式 */
        QLabel {
            color: #555555;
        }

        /* 滚动条样式 */
        QScrollBar:vertical {
            background: #f0f0f0;
            width: 12px;
            margin: 0px;
        }
        QScrollBar::handle:vertical {
            background: #c0c0c0;
            border-radius: 6px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background: #a0a0a0;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            height: 0px;
        }
    )");
}

QPushButton* TicketAdminDialog::createButton(const QString& text, const QString& color, const QString& hoverColor, int minWidth) {
    QPushButton* btn = new QPushButton(text, this);
    btn->setMinimumSize(minWidth, 36);
    btn->setCursor(Qt::PointingHandCursor);

    QString style = QString(
        "QPushButton { "
        "    background-color: %1; "
        "    color: white; "
        "    border: none; "
        "    border-radius: 6px; "
        "    padding: 8px 12px; "
        "    font-weight: bold; "
        "} "
        "QPushButton:hover { "
        "    background-color: %2; "
        "} "
        "QPushButton:pressed { "
        "    background-color: %1; "
        "} "
        "QPushButton:disabled { "
        "    background-color: #bdc3c7; "
        "    color: #7f8c8d; "
        "}"
    ).arg(color, hoverColor);

    btn->setStyleSheet(style);
    return btn;
}

QPushButton* TicketAdminDialog::createActionButton(const QString& text, const QString& color, const QString& hoverColor) {
    QPushButton* btn = new QPushButton(text, this);
    btn->setMinimumSize(60, 28);
    btn->setCursor(Qt::PointingHandCursor);

    QString style = QString(
        "QPushButton { "
        "    background-color: %1; "
        "    color: white; "
        "    border: none; "
        "    border-radius: 4px; "
        "    padding: 4px 8px; "
        "    font-size: 9pt; "
        "    font-weight: bold; "
        "} "
        "QPushButton:hover { "
        "    background-color: %2; "
        "} "
        "QPushButton:pressed { "
        "    background-color: %1; "
        "} "
        "QPushButton:disabled { "
        "    background-color: #bdc3c7; "
        "    color: #7f8c8d; "
        "}"
    ).arg(color, hoverColor);

    btn->setStyleSheet(style);
    return btn;
}